'use strict'
let Player = require('./model').Player
let Ids = require('./model').Ids
let serverConfig = require('../../config/serverConfig').serverConfig
let serverId = serverConfig.serverId

exports.newAndSave = function(p, callback) {
    Ids.findAndModify({
        _id: serverId
    }, [], {
        $inc: {
            playerId: 1
        }
    }, {}, function(err, res) {
        if (err || !res.value) throw err;
        let id = res.value.playerId * 1000 + serverId //id后面3位是服务器id
        p._id = id
        p.registerTime = new Date().getTime()
        let player = new Player(p)
        player.save(callback)
    });

}

/**
 * 根据查询条件, 查找一个角色
 */
exports.getPlayerByQuery = function(query, callback) {
    Player.findOne(query, function(err, res) {
        if (!err && res) {
            res = JSON.parse(JSON.stringify(res))
        }
        callback(err, res)
    })
}

/**
 * 根据查询条件, 查找角色
 */
exports.getPlayersByQuery = function(query, callback) {
    Player.find(query, function(err, res) {
        callback(err, res)
    })
}

/**
 * 根据查询条件, 删除角色
 */
exports.removePlayerByQuery = function(query, callback) {
    Player.remove(query, callback)
}

/**
 * 根据查询条件, 更新角色
 */
exports.savePlayerById = function(playerId, field, callback) {
    field.basicInfo.maxHp = field.fightAttri.maxHp
    field.basicInfo.hp = field.fightAttri.hp
    let player = JSON.parse(JSON.stringify(field))
    delete player.bag.itemsById
    player = new Player(player, null, true)
    Player.update({
        _id: playerId
    }, player, {}, callback)
}

exports.updatePlayerById = function(playerId, field, callback) {
    Player.update({
        _id: playerId
    }, field, {}, callback)
}
